import React from 'react'
import { Link } from 'react-router-dom'
import { Card, Breadcrumb, Form, Button, Radio, DatePicker } from 'antd'
import 'moment/locale/zh-cn'
import locale from 'antd/es/date-picker/locale/zh_CN'
import { Table, Tag, Space, Modal } from 'antd'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
import img404 from '@/assets/error.png'
import { useDispatch } from 'react-redux'
import { useEffect } from 'react'
//
import {
  getChannelAction,
  getArticleAction,
  delArticleAction,
} from '@/store/actions/article'

import { useSelector } from 'react-redux'
import { useRef } from 'react'
import { useHistory } from 'react-router-dom'
import Channel from '@/components/Channel'

const { RangePicker } = DatePicker

// 优化文章状态的处理
const articleStatus = {
  0: { color: 'yellow', text: '草稿' },
  1: { color: '#ccc', text: '待审核' },
  2: { color: 'green', text: '审核通过' },
  3: { color: 'red', text: '审核失败' },
}
export default function Article() {
  // 1.获取文章频道列表
  const dispatch = useDispatch()
  const history = useHistory()
  useEffect(() => {
    dispatch(getChannelAction())
    dispatch(getArticleAction({}))
  }, [dispatch])
  const { list, total, page, pageSize } = useSelector((store) => {
    return store.article
  })
  // 使用useref 记录过滤条件数据
  const filters = useRef({})
  const onFilter = ({ status, channel_id, date }) => {
    console.log('过滤条件', status, channel_id, date)
    const params = { channel_id }
    // 排除全部
    if (status !== -1) {
      params.status = status
    }
    // 判断一个是否是 '' null undefined
    if (!!date) {
      params.begin_pubdate = date[0].format('YYYY--MM--DD HH:mm:ss')
      params.end_pubdate = date[1].format('YYYY--MM--DD HH:mm:ss')
    }
    filters.current = params
    dispatch(getArticleAction(params))
  }
  // 文章列表切换分页事件
  const onPageChange = (page, pageSize) => {
    console.log(page, pageSize)
    const params = {
      page,
      per_page: pageSize,
      ...filters.current,
    }
    dispatch(getArticleAction(params))
  }
  // 删除文章
  const delArticle = (data) => {
    Modal.confirm({
      title: '提示',
      content: `确认要删除:${data.title}嘛?`,
      onOk() {
        console.log('确定删除')
        dispatch(delArticleAction(data.id, filters.current))
      },
    })
  }
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      render: (cover) => {
        return <img src={cover || img404} width={200} height={150} alt="" />
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
      width: 220,
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (status) => (
        <Tag color={articleStatus[status].color}>
          {articleStatus[status].text}
        </Tag>
      ),
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      render: (data) => {
        return (
          <Space size="middle">
            {/* 修改文章 */}
            <Button
              onClick={() => {
                history.push({
                  pathname: `/home/publish/${data.id}`,
                })
              }}
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
            />
            {/* 删除文章 */}
            <Button
              type="primary"
              danger
              shape="circle"
              onClick={() => delArticle(data)}
              icon={<DeleteOutlined />}
            />
          </Space>
        )
      },
    },
  ]

  return (
    <div>
      <>
        <Card
          title={
            <Breadcrumb separator=">">
              <Breadcrumb.Item>
                <Link to="/home">首页</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>内容管理</Breadcrumb.Item>
            </Breadcrumb>
          }
          style={{ marginBottom: 20 }}>
          <Form onFinish={onFilter} initialValues={{ status: -1 }}>
            <Form.Item label="状态" name="status">
              <Radio.Group>
                <Radio value={-1}>全部</Radio>
                <Radio value={0}>草稿</Radio>
                <Radio value={1}>待审核</Radio>
                <Radio value={2}>审核通过</Radio>
                <Radio value={3}>审核失败</Radio>
              </Radio.Group>
            </Form.Item>

            <Form.Item label="频道" name="channel_id">
              <Channel width={400}></Channel>
            </Form.Item>

            <Form.Item label="日期" name="date">
              <RangePicker locale={locale}></RangePicker>
            </Form.Item>

            <Form.Item>
              <Button type="primary" htmlType="submit">
                筛选
              </Button>
            </Form.Item>
          </Form>
        </Card>
        {/* table区域 */}
        <Card title={`根据筛选条件共查询到 ${total} 条结果：`}>
          <Table
            pagination={{
              position: ['bottomLeft'],
              current: page,
              pageSize,
              total,
              showSizeChanger: true,
              onChange: onPageChange, //页码或pageSize 改变的回调
            }}
            rowKey="id"
            columns={columns}
            dataSource={list}
          />
        </Card>
      </>
    </div>
  )
}
